package net.simo.servicebook.controller;

import java.io.IOException;
import java.io.Serializable;
import java.util.List;

import javax.enterprise.context.Conversation;
import javax.enterprise.context.ConversationScoped;
import javax.enterprise.inject.Produces;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.inject.Inject;
import javax.inject.Named;

import net.simo.servicebook.model.Person;
import net.simo.servicebook.model.security.Role;
import net.simo.servicebook.model.security.User;
import net.simo.servicebook.service.UserManager;

@Named
@ConversationScoped
public class UserController implements Serializable {

	private static final long serialVersionUID = -541903542946814334L;

	@Inject
	private Conversation conversation;
	@Inject
	private UserManager manager;
	private User newUser;
	private String rePassword;
	private List<Role> roles;

	public List<Role> getRoles() {
		return roles;
	}

	public void setRoles(List<Role> roles) {
		this.roles = roles;
	}

	@Produces
	public String getRePassword() {
		return rePassword;
	}

	public void setRePassword(String rePassword) {
		this.rePassword = rePassword;
	}

	@Produces
	@Named
	public User getNewUser() {
		return newUser;
	}

	public void setNewUser(User newUser) {
		this.newUser = newUser;
	}

	public void createNewUser(Person person) {
		String redirectUrl = "/userPanel.jsf";
		newUser = new User();
		newUser.setPerson(person);
		newUser.setRole(new Role());

		try {
			FacesContext.getCurrentInstance().getExternalContext()
					.redirect(redirectUrl);
		} catch (Exception e) {
			// TODO: handle exception
		}
	}

	public void shit(String string) {
		System.out.println("shit" + string);
	}

	public void saveUser() {
		String redirectUrl = "/registration.jsf";
		if (newUser.getPassword().equals(rePassword)) {
			manager.saveUser(newUser);
			newUser = null;
			try {
				FacesContext.getCurrentInstance().getExternalContext()
						.redirect(redirectUrl);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			// conversation.end();
		} else {
			FacesContext facesContext = FacesContext.getCurrentInstance();
			facesContext.addMessage("newUserForm:userRePassword",
					new FacesMessage(FacesMessage.SEVERITY_ERROR,
							"Fuck this shit",
							"Nigga the password does not match"));
		}
	}

	public List<Role> selectRole() {
		roles = manager.selectRole();
		return roles;
	}

	public void cancelUser() {
		newUser = null;
	}
}
